package com.jse.web;

import java.util.concurrent.ConcurrentHashMap;

import com.jse.Log;
import com.jse.util.PathMatcher;

public class Router {
	
	public static final Log log=Log.get(Router.class);
	private Router() {}
	public static final PathMatcher PATH_MATCHER=new PathMatcher();
	public static final Router router=new Router();
	public static final JsRoute JSRoute= new JsRoute();
	
	public static final ConcurrentHashMap<String,Route> ROUTES=new ConcurrentHashMap<>();
	public static final ConcurrentHashMap<String,Route> REGROUTES=new ConcurrentHashMap<>();

	public static Router addRoute(Route r) {ROUTES.putIfAbsent(r.path(),r);return router;}
	public static Router addRoute(String path,Route r) {
		if(PATH_MATCHER.isPattern(path)) {
			REGROUTES.putIfAbsent(path,r);
			log.info("addRoute PATH_MATCHER {}",path);
		}else {
			ROUTES.putIfAbsent(path,r);
			log.info("addRoute ROUTES {}",path);
		}
		return router;
	}
	public static Router setRoute(String path,Route r) {
		if(PATH_MATCHER.isPattern(path)) {
			REGROUTES.put(path,r);
		}else {
			ROUTES.put(path,r);
			
		}
		return router;
	}

	public static Route getRoute(Ctx tbl) {
		Route r=ROUTES.get(tbl.getPath());
		if(r==null) {
			r=ROUTES.get(tbl.getMapping());//匹配如默认的数字/11为/id /为/index
			if(r==null) {//开始匹配带正则的
				var mapping=REGROUTES.searchKeys(100,(k)->PATH_MATCHER.match(k,tbl.getPath())?k:null);
		        if (mapping!= null) {
		        	if(mapping.contains("{")) {
		        		var mp=PATH_MATCHER.extractUriTemplateVariables(mapping,tbl.getMapping());
			        	mp.forEach((k,v)->{tbl.putIfAbsent(k,v);});//填充到默认参数
		        	}
		        	return REGROUTES.get(mapping);
		        }//未找到 最后走jsrouter
			}
		}else {
			return r;
		}
		return JSRoute;
	}
	
	public static void main(String[] args) {
		var b=PATH_MATCHER.match("/jse/**","/jse/captcha/id");
		var b1=PATH_MATCHER.matchStart("/jse/**","/jse/captcha/id");
		System.err.println(b+"="+b1);
	}

}
